<template>
  <div class="add-traffic-car">
    <el-form v-if="!isUpd" class="add-traffic-car-fm" :model="fm.ps" :ref="fm.fname">
      <el-row type="flex">
        <el-form-item label="用车单位" label-width="80px" style="margin-right: 30px;"
          :rules="[{ required: true, message: '请搜索并选择用车单位', trigger: 'change' }]">
          <el-input v-model="queryCusPageList_find" @change="queryCusPageList_change" placeholder="搜索用车单位"
            style="width: 120px;">
          </el-input>
          <el-select v-model="fm.ps.useCarUname" clearable filterable :remote="true" :remote-method="queryCusPageList"
            :placeholder="'选择用车单位选择'" style="width: 145px;">
            <el-option v-for="it in cusList" :key="it.baseUserId.uname"
              :label="it.baseUserId.realName + '【' + it.unitName + '】'" :value="it.baseUserId.uname"
              @click.native="selUseCarCus(it)">
              <span>{{ it.baseUserId.realName + '【' + it.unitName + '】' }}</span>
              <span>{{ it.baseUserId.phone }}</span>
            </el-option>
          </el-select>

          <i class="el-icon-circle-plus add-btn" title="添加用车单位" @click="setAddCusMd({ state: true })"></i>
        </el-form-item>

        <el-form-item label="联系人" prop="operator" label-width="65px" style="margin-right: 10px;"
          :rules="[{ required: true, message: '请选择联系人', trigger: 'change' }]">
          <el-select v-model="fm.ps.operator" clearable filterable placeholder="联系人选择" style="width: 110px;">
            <el-option v-for="it in operatorList" :key="it.uname" :label="it.realName" :value="it.uname">
              <span>{{ it.realName }}</span>
              <span style="font-size: 12px;">{{ it.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="乘车人" prop="routeLink.name" label-width="65px" style="margin-right: 10px;" :rules="[
          { required: true, message: '请输入乘车人姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]">
          <el-input v-model="fm.ps.routeLink.name" placeholder="乘车人姓名" style="width: 100px;">
          </el-input>
        </el-form-item>

        <el-form-item label="电话" prop="routeLink.phone" label-width="50px" style="margin-right: 10px;" :rules="[
          { required: true, message: '请输入客户电话', trigger: 'blur' },
          { min: 11, max: 11, message: '电话号码为数字', trigger: 'blur' }
        ]">
          <el-input v-model="fm.ps.routeLink.phone" placeholder="客户电话" style="width: 110px;">
          </el-input>
        </el-form-item>

        <el-form-item label="业务员" prop="serviceMan.uname" label-width="65px" style="margin-right: 10px;"
          :rules="[{ required: true, message: '请选择业务员', trigger: 'change' }]">
          <el-select v-model="fm.ps.serviceMan.uname" clearable filterable placeholder="业务员选择" style="width: 110px;">
            <el-option v-for="it in serviceManList" :key="it.baseUserId.uname" :label="it.baseUserId.realName"
              :value="it.baseUserId.uname" @click.native="selServiceMan(it.baseUserId)">
              <span>{{ it.baseUserId.realName }}</span>
              <span>{{ it.baseUserId.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="行程简称" prop="routeShort" style="margin-bottom: 0;" label-width="80px" :rules="[
          { required: true, message: '请选择行程简称', trigger: 'change' }]">
          <el-input maxlength="5" v-if="fm.ps.routeShort == '包车'" v-model="routeShort_value" placeholder="行程简称"
            show-word-limit style="width: 110px; margin-right:10px"></el-input>
          <el-select @change="routeShortchange" v-model="fm.ps.routeShort" clearable placeholder="行程简称 "
            style="width: 115px;">
            <el-option v-for="item in JourneyAbbreviation" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>


        </el-form-item>

        <el-form-item prop="fixedCar" style="width: 80px;margin-right: 10px;" label-width="0px">
          <el-checkbox v-model="fm.ps.fixedCar" :true-label="0" :false-label="1">
            固定车
          </el-checkbox>
        </el-form-item>

        <el-form-item prop="fixedDriver" style="width: 70px;" label-width="0px">
          <el-checkbox v-model="fm.ps.fixedDriver" :true-label="0" :false-label="1">
            固定人
          </el-checkbox>
        </el-form-item>
      </el-row>

      <el-row type="flex" class="jt-car-line">
        <el-form-item prop="seDate" style="margin-right: 10px;" :rules="[
          { required: true, message: '请选择日期起止', trigger: 'blur' }
        ]">
          <el-date-picker v-model="fm.ps.seDate" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="yyyy-MM-dd" style="width: 215px;">
          </el-date-picker>
        </el-form-item>

        <el-form-item prop="repeatWay" style="margin-right: 10px;" :rules="[
          { required: true, message: '请选择重复方式', trigger: 'blur' },
        ]">
          <el-select v-model="fm.ps.repeatWay" multiple collapse-tags placeholder="重复方式" style="width: 160px"
            @change="selRepeatWay">
            <el-option v-for="item in repeatWayList" :key="item.val" :label="item.text" :value="item.val">
            </el-option>
            <i slot="prefix" style="line-height: 26px;">
              <SvgIcon :svgName="'repeat'" :width="'16px'" :height="'16px'" />
            </i>
          </el-select>
        </el-form-item>

        <el-form-item prop="goStime" style="margin-right: 10px;" :rules="[
          { required: true, message: '请选择去程开始时间', trigger: 'blur' },
          { pattern: /^(?:(?:[0-2][0-3])|(?:[0-1][0-9])):[0-5][0-9]$/, message: '时间格式错误' }
        ]">
          <TimeInp :name="'goStime'" :defval="fm.ps.goStime" :tip="'去程开始时间'" :width="135" :iconName="'stime'"
            @pclick="timeInp" />
        </el-form-item>

        <el-form-item prop="goPoints" style="width: 150px;margin-right: 10px;" :rules="[
          { required: true, message: '请选择去程线路', trigger: ['change', 'blur'] },
        ]">
          <MapPointList :name="'goPoints'" :placeholder="'去程线路'" :vallist="fm.ps.goPoints" @handleSel="setPoint" />
        </el-form-item>

        <el-form-item prop="goEtime" style="margin-right: 10px;" :rules="[
          { required: true, message: '请选择去程结束时间', trigger: 'blur' },
          { pattern: /^(?:(?:[0-2][0-3])|(?:[0-1][0-9])):[0-5][0-9]$/, message: '时间格式错误' }
        ]">
          <TimeInp :name="'goEtime'" :defval="fm.ps.goEtime" :tip="'去程结束时间'" :width="135" :iconName="'etime'"
            @pclick="timeInp" />
        </el-form-item>

        <el-form-item prop="spaceDays" style="margin-right: 10px;" :rules="[
          { required: true, message: '请输入间隔天数', trigger: 'blur' },
          this.$rules.isPosInt()
        ]">
          <el-input v-model.number="fm.ps.spaceDays" placeholder="间隔天数" style="width: 110px;">
            <span slot="suffix">天</span>
            <i slot="prefix" style="line-height: 26px;">
              <SvgIcon :svgName="'space-days'" :width="'16px'" :height="'16px'" />
            </i>
          </el-input>
        </el-form-item>

        <el-form-item prop="backStime" style="margin-right: 10px;" :rules="[
          { required: true, message: '请选择回程开始时间', trigger: 'blur' },
          { pattern: /^(?:(?:[0-2][0-3])|(?:[0-1][0-9])):[0-5][0-9]$/, message: '时间格式错误' }
        ]">
          <TimeInp :name="'backStime'" :defval="fm.ps.backStime" :tip="'回程开始时间'" :width="135" :iconName="'stime'"
            @pclick="timeInp" />
        </el-form-item>

        <el-form-item prop="backPoints" style="width: 150px;margin-right: 10px;" :rules="[
          { required: true, message: '请选择回程线路', trigger: ['change', 'blur'] },
        ]">
          <MapPointList :name="'backPoints'" :placeholder="'回程线路'" :vallist="fm.ps.backPoints" @handleSel="setPoint" />
        </el-form-item>

        <el-form-item prop="backEtime" style="margin-right: 10px;" :rules="[
          { required: true, message: '请选择回程结束时间', trigger: 'blur' },
          { pattern: /^(?:(?:[0-2][0-3])|(?:[0-1][0-9])):[0-5][0-9]$/, message: '时间格式错误' }
        ]">
          <TimeInp :name="'backEtime'" :defval="fm.ps.backEtime" :tip="'回程结束时间'" :width="135" :iconName="'etime'"
            @pclick="timeInp" />
        </el-form-item>

        <el-form-item prop="wayHighSpeed">
          <el-input placeholder="途径高速" clearable v-model="fm.ps.wayHighSpeed" :style="{ 'width': '130px' }">
            <i slot="prefix" style="line-height: 26px;">
              <SvgIcon :svgName="'hight-speed'" :width="'16px'" :height="'16px'" />
            </i>
          </el-input>
        </el-form-item>
      </el-row>

      <el-row type="flex">
        <el-form-item label="座位" prop="seats" style="margin-right: 10px;" label-width="50px" :rules="[
          { required: true, message: '请填写座位数', trigger: 'blur' },
          this.$rules.isPosInt()
        ]">
          <el-input v-model.number="fm.ps.seats" placeholder="座位数" style="width: 115px;">
            <span slot="suffix">座</span>
          </el-input>
        </el-form-item>

        <el-form-item label="运价" prop="transportPrice" style="margin-right: 10px;" label-width="50px" :rules="[
          { required: true, message: '请输入运价', trigger: 'blur' },
          this.$rules.isFloat()
        ]">
          <el-input v-model.number="fm.ps.transportPrice" placeholder="运价" @blur="calcOrderTotalPrice"
            style="width: 115px;">
            <span slot="suffix">￥</span>
          </el-input>
        </el-form-item>


        <el-form-item label="天数" prop="cars" style="margin-right: 10px;" label-width="65px" :rules="[
          { required: true, message: '请填写天数', trigger: 'blur' },
          this.$rules.isPosInt()
        ]">
          <el-input v-model.number="fm.ps.useCarDays" placeholder="天数" @blur="calcOrderTotalPrice"
            style="width: 70px;"><span slot="suffix">天</span></el-input>
        </el-form-item>

        <el-form-item label="车辆数" prop="cars" style="margin-right: 10px;" label-width="65px" :rules="[
          { required: true, message: '请填写车辆数', trigger: 'blur' },
          this.$rules.isPosInt()
        ]">
          <el-input v-model.number="fm.ps.cars" placeholder="车辆数" @blur="calcOrderTotalPrice" style="width: 80px;">
            <span slot="suffix">辆</span>
          </el-input>
        </el-form-item>

        <el-form-item label="其他费用" prop="otherFees" style="margin-right: 10px;" label-width="70px" :rules="[
          { required: false, message: '请输入其他费用', trigger: 'blur' },
          this.$rules.isFloat()
        ]">
          <el-input v-model.number="fm.ps.otherFees" placeholder="其他费用" @blur="calcOrderTotalPrice"
            style="width: 110px;"><span slot="suffix">￥</span></el-input>
        </el-form-item>

        <el-form-item label="师傅现收" prop="remindRouteCash" style="margin-right: 10px;" label-width="70px" :rules="[
          { required: false, message: '请输入师傅现收', trigger: 'blur' },
          this.$rules.isFloat()
        ]">
          <el-input v-model.number="fm.ps.remindRouteCash" placeholder="师傅现收" @blur="calcOrderTotalPrice"
            style="width: 110px;"><span slot="suffix">￥</span></el-input>
        </el-form-item>

        <el-form-item label="订单总价" prop="orderTotalPrice" label-width="70px" style="margin-right: 10px;">
          <el-input v-model.number="fm.ps.orderTotalPrice" placeholder="自动计算" :readonly="true" style="width: 130px;"><span
              slot="suffix">￥</span></el-input>
        </el-form-item>

        <el-form-item label="定金" prop="deposit" label-width="40px" style="margin-right: 10px;" :rules="[
          { required: false, message: '请输入定金', trigger: 'blur' },
          this.$rules.isFloat()
        ]">
          <el-input v-model.number="fm.ps.deposit" placeholder="定金" style="width: 120px;">
            <span slot="suffix">￥</span>
          </el-input>
        </el-form-item>
      </el-row>

      <el-row type="flex" class="text-note">
        <el-form-item label="行程" prop="routeDetail" label-width="35px">
          <el-input type="textarea" autosize placeholder="行程详情内容（不能修改）" :value="fm.ps.routeDetail.replace(/@/g, '\n')"
            :readonly="true" style="width: 610px;">
          </el-input>
        </el-form-item>

        <el-form-item label="客户备注" prop="cusNote" label-width="35px">
          <el-input type="textarea" autosize placeholder="客户备注（所有人都能看到）" maxlength="100" show-word-limit
            v-model="fm.ps.cusNote" style="width: 260px;">
          </el-input>
        </el-form-item>

        <el-form-item label="驾驶员备注" prop="driverNote" label-width="35px">
          <el-input type="textarea" autosize placeholder="驾驶员备注内容" maxlength="100" show-word-limit
            v-model="fm.ps.driverNote" style="width: 260px;">
          </el-input>
        </el-form-item>

        <el-form-item label="业务员备注" prop="salesmanNote" label-width="35px">
          <el-input type="textarea" autosize placeholder="业务员备注内容" maxlength="100" show-word-limit
            v-model="fm.ps.salesmanNote" style="width: 260px;">
          </el-input>
        </el-form-item>
      </el-row>

      <el-row>
        <el-col :span="24">
          <div style="text-align: center;">
            <el-button type="primary" @click="onSubmitFm(1)" :disabled="fm.sb.load">立即添加</el-button>
            <el-button type="warning" @click="onSubmitFm(3)" :disabled="fm.sb.load">保存并继续</el-button>
          </div>
        </el-col>
      </el-row>

      <el-row>
        <div class="page-explain">
          <span>保存行程订单：保存成功后关闭页面。保存并继续：保存成功后页面不关闭信息不清空。</span>
        </div>
      </el-row>
    </el-form>


    <!-- 修改表单 -->
    <el-form v-if="isUpd" class="upd-traffic-car-fm" :model="fm.ps" :ref="fm.fname">
      <el-row type="flex">
        <el-form-item label="用车单位" prop="useCarUname" label-width="80px" style="margin-right: 30px;"
          :rules="[{ required: true, message: '请搜索并选择用车单位', trigger: 'change' }]">
          <el-input v-model="queryCusPageList_find" @change="queryCusPageList_change" placeholder="搜索用车单位"
            style="width: 120px;">
          </el-input>
          <el-select v-model="fm.ps.useCarUname" clearable filterable :remote="true" :remote-method="queryCusPageList"
            :placeholder="'搜索选择用车单位'" style="width: 135px;">
            <el-option v-for="it in cusList" :key="it.baseUserId.uname"
              :label="it.baseUserId.realName + '【' + it.unitName + '】'" :value="it.baseUserId.uname"
              @click.native="selUseCarCus(it)">
              <span>{{ it.baseUserId.realName + '【' + it.unitName + '】' }}</span>
              <span>{{ it.baseUserId.phone }}</span>
            </el-option>
          </el-select>

          <i class="el-icon-circle-plus add-btn" title="添加用车单位" @click="setAddCusMd({ state: true })"></i>
        </el-form-item>

        <el-form-item label="联系人" prop="operator" label-width="65px" style="margin-right: 10px;"
          :rules="[{ required: true, message: '请选择联系人', trigger: 'change' }]">
          <el-select v-model="fm.ps.operator" clearable filterable placeholder="联系人选择" style="width: 110px;">
            <el-option v-for="it in operatorList" :key="it.uname" :label="it.realName" :value="it.uname">
              <span>{{ it.realName }}</span>
              <span style="font-size: 12px;">{{ it.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="乘车人" prop="routeLink.name" label-width="65px" style="margin-right: 10px;" :rules="[
          { required: true, message: '请输入乘车人姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]">
          <el-input v-model="fm.ps.routeLink.name" placeholder="乘车人姓名" style="width: 100px;">
          </el-input>
        </el-form-item>

        <el-form-item label="电话" prop="routeLink.phone" label-width="50px" style="margin-right: 10px;" :rules="[
          { required: true, message: '请输入客户电话', trigger: 'blur' },
          { min: 11, max: 11, message: '电话号码为数字', trigger: 'blur' }
        ]">
          <el-input v-model="fm.ps.routeLink.phone" placeholder="客户电话" style="width: 110px;">
          </el-input>
        </el-form-item>

        <el-form-item label="业务员" prop="serviceMan.uname" label-width="65px" style="margin-right: 10px;"
          :rules="[{ required: true, message: '请选择业务员', trigger: 'change' }]">
          <el-select v-model="fm.ps.serviceMan.uname" clearable filterable placeholder="业务员选择" style="width: 110px;">
            <el-option v-for="it in serviceManList" :key="it.baseUserId.uname" :label="it.baseUserId.realName"
              :value="it.baseUserId.uname" @click.native="selServiceMan(it.baseUserId)">
              <span>{{ it.baseUserId.realName }}</span>
              <span>{{ it.baseUserId.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="行程简称" prop="routeShort" style="margin-right: 20px;" label-width="80px" :rules="[
          { required: true, message: '请输入行程简称', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ]">
          <el-input v-model="fm.ps.routeShort" placeholder="行程简称" maxlength="15" show-word-limit style="width: 180px;">
          </el-input>
        </el-form-item>

        <el-form-item prop="fixedCar" style="width: 80px;margin-right: 10px;" label-width="0px">
          <el-checkbox v-model="fm.ps.fixedCar" :true-label="0" :false-label="1">
            固定车
          </el-checkbox>
        </el-form-item>

        <el-form-item prop="fixedDriver" style="width: 70px;" label-width="0px">
          <el-checkbox v-model="fm.ps.fixedDriver" :true-label="0" :false-label="1">
            固定人
          </el-checkbox>
        </el-form-item>
      </el-row>

      <el-row type="flex" class="jt-car-line">
        <el-form-item prop="goStime" style="margin-right: 10px;" :rules="[
          { required: true, message: '请选择去程开始时间', trigger: 'blur' },
          { pattern: /^(?:(?:[0-2][0-3])|(?:[0-1][0-9])):[0-5][0-9]$/, message: '时间格式错误' }
        ]">
          <TimeInp :name="'goStime'" :defval="fm.ps.goStime" :tip="'去程开始时间'" :width="135" :iconName="'stime'"
            @pclick="timeInp" />
        </el-form-item>

        <el-form-item prop="goPoints" style="width: 150px;margin-right: 10px;" :rules="[
          { required: true, message: '请选择去程线路', trigger: ['change', 'blur'] },
        ]">
          <MapPointList :name="'goPoints'" :placeholder="'去程线路'" :vallist="fm.ps.goPoints" @handleSel="setPoint" />
        </el-form-item>

        <el-form-item prop="goEtime" style="margin-right: 10px;" :rules="[
          { required: true, message: '请选择去程结束时间', trigger: 'blur' },
          { pattern: /^(?:(?:[0-2][0-3])|(?:[0-1][0-9])):[0-5][0-9]$/, message: '时间格式错误' }
        ]">
          <TimeInp :name="'goEtime'" :defval="fm.ps.goEtime" :tip="'去程结束时间'" :width="135" :iconName="'etime'"
            @pclick="timeInp" />
        </el-form-item>

        <el-form-item prop="backStime" style="margin-right: 10px;" :rules="[
          { required: true, message: '请选择回程开始时间', trigger: 'blur' },
          { pattern: /^(?:(?:[0-2][0-3])|(?:[0-1][0-9])):[0-5][0-9]$/, message: '时间格式错误' }
        ]">
          <TimeInp :name="'backStime'" :defval="fm.ps.backStime" :tip="'回程开始时间'" :width="135" :iconName="'stime'"
            @pclick="timeInp" />
        </el-form-item>

        <el-form-item prop="backPoints" style="width: 150px;margin-right: 10px;" :rules="[
          { required: true, message: '请选择回程线路', trigger: ['change', 'blur'] },
        ]">
          <MapPointList :name="'backPoints'" :placeholder="'回程线路'" :vallist="fm.ps.backPoints" @handleSel="setPoint" />
        </el-form-item>

        <el-form-item prop="backEtime" style="margin-right: 10px;" :rules="[
          { required: true, message: '请选择回程结束时间', trigger: 'blur' },
          { pattern: /^(?:(?:[0-2][0-3])|(?:[0-1][0-9])):[0-5][0-9]$/, message: '时间格式错误' }
        ]">
          <TimeInp :name="'backEtime'" :defval="fm.ps.backEtime" :tip="'回程结束时间'" :width="135" :iconName="'etime'"
            @pclick="timeInp" />
        </el-form-item>

        <el-form-item prop="wayHighSpeed">
          <el-input placeholder="途径高速" clearable v-model="fm.ps.wayHighSpeed" :style="{ 'width': '510px' }">
            <i slot="prefix" style="line-height: 26px;">
              <SvgIcon :svgName="'hight-speed'" :width="'16px'" :height="'16px'" />
            </i>
          </el-input>
        </el-form-item>
      </el-row>

      <el-row type="flex">
        <el-form-item label="座位" prop="seats" style="margin-right: 10px;" label-width="50px" :rules="[
          { required: true, message: '请填写座位数', trigger: 'blur' },
          this.$rules.isPosInt()
        ]">
          <el-input v-model.number="fm.ps.seats" placeholder="座位数" style="width: 115px;">
            <span slot="suffix">座</span>
          </el-input>
        </el-form-item>

        <el-form-item label="运价" prop="transportPrice" style="margin-right: 10px;" label-width="50px" :rules="[
          { required: true, message: '请输入运价', trigger: 'blur' },
          this.$rules.isFloat()
        ]">
          <el-input v-model.number="fm.ps.transportPrice" placeholder="运价" @blur="calcOrderTotalPrice"
            style="width: 115px;">
            <span slot="suffix">￥</span>
          </el-input>
        </el-form-item>

        <el-form-item label="其他费用" prop="otherFees" style="margin-right: 10px;" label-width="70px" :rules="[
          { required: false, message: '请输入其他费用', trigger: 'blur' },
          this.$rules.isFloat()
        ]">
          <el-input v-model.number="fm.ps.otherFees" placeholder="其他费用" @blur="calcOrderTotalPrice" style="width: 130px;">
            <span slot="suffix">￥</span>
          </el-input>
        </el-form-item>

        <el-form-item label="师傅现收" prop="remindRouteCash" style="margin-right: 10px;" label-width="70px" :rules="[
          { required: false, message: '请输入师傅现收', trigger: 'blur' },
          this.$rules.isFloat()
        ]">
          <el-input v-model.number="fm.ps.remindRouteCash" placeholder="师傅现收" @blur="calcOrderTotalPrice"
            style="width: 130px;">
            <span slot="suffix">￥</span>
          </el-input>
        </el-form-item>

        <el-form-item label="派单价格" prop="disPrice" label-width="70px" style="margin-right: 10px;" :rules="[
          { required: false, message: '请输入派单价格', trigger: 'blur' },
          this.$rules.isFloat()
        ]">
          <el-input v-model.number="fm.ps.disPrice" placeholder="派单价格" style="width: 570px;"><span
              slot="suffix">￥</span></el-input>
        </el-form-item>
      </el-row>

      <el-row type="flex" class="text-note">
        <el-form-item label="行程" prop="routeDetail" label-width="35px">
          <el-input type="textarea" autosize placeholder="行程详情内容（不能修改）" :value="fm.ps.routeDetail.replace(/@/g, '\n')"
            :readonly="true" style="width: 610px;">
          </el-input>
        </el-form-item>

        <el-form-item label="客户备注" prop="cusNote" label-width="35px">
          <el-input type="textarea" autosize placeholder="客户备注（所有人都能看到）" maxlength="100" show-word-limit
            v-model="fm.ps.cusNote" style="width: 220px;">
          </el-input>
        </el-form-item>

        <el-form-item label="驾驶员备注" prop="driverNote" label-width="35px">
          <el-input type="textarea" autosize placeholder="驾驶员备注内容" maxlength="100" show-word-limit
            v-model="fm.ps.driverNote" style="width: 220px;">
          </el-input>
        </el-form-item>

        <el-form-item label="业务员备注" prop="salesmanNote" label-width="35px">
          <el-input type="textarea" autosize placeholder="业务员备注内容" maxlength="100" show-word-limit
            v-model="fm.ps.salesmanNote" style="width: 220px;">
          </el-input>
        </el-form-item>
      </el-row>

      <el-row>
        <el-col :span="2">
          <el-checkbox v-model="fm.ps.isNotice" :true-label="1" :false-label="0">
            通知驾驶员
          </el-checkbox>
        </el-col>

        <el-col :span="22">
          <div style="text-align: center;">
            <el-button type="primary" @click="onSubmitFm(1)" :disabled="fm.sb.load">修 改</el-button>

            <el-button type="success" v-if="!fm.ps.isCopy">
              <el-popover class="tb-popover" trigger="click" placement="top" :width="1000">
                <el-table :ref="dg.tbName" :data="dg.list" row-key="orderNum" border fit :height="40 * dg.list.length"
                  :max-height="500" @selection-change="selRowChange" style="min-height: 100px;">
                  <el-table-column type="selection" width="40"></el-table-column>
                  <el-table-column prop="orderNum" label="行程编号" width="140"></el-table-column>
                  <el-table-column prop="dayRoutes.0.goDate" label="出发日期" width="80"></el-table-column>
                  <el-table-column prop="routeDetail" label="行程详情"></el-table-column>
                </el-table>
                <div slot="reference">同步修改订单</div>
              </el-popover>
            </el-button>
          </div>
        </el-col>
      </el-row>

      <el-row>
        <div class="page-explain">
          <span>保存行程订单：保存成功后关闭页面。保存并继续：保存成功后页面不关闭信息不清空。</span>
        </div>
      </el-row>
    </el-form>

    <AddCus v-if="addCusMd.state" @myClick="setAddCusMd" @reloadDg="setCusDat" />

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import SvgIcon from '@/components/SvgIcon';
import TimeInp from '@/components/TimeInp';
import AddCus from '../../add-cus';
import MapPointInp from '@/components/MapPointInp';
import MapPointList from '@/components/MapPointList';

import * as commonSer from '@/api/services/common.service';
import * as orderService from '@/api/services/order.service';

export default {
  name: 'AddTrafficCar',
  props: ['order', 'allServiceManList'],
  components: {
    SvgIcon,
    TimeInp,
    AddCus,
    MapPointInp,
    MapPointList,
  },
  computed: { ...mapGetters(['lunitNum', 'uname']) },
  data() {
    return {
      queryCusPageList_find: "",
      JourneyAbbreviation: [{
        value: '送天府',
        label: '送天府'
      }, {
        value: '接天府',
        label: '接天府'
      }, {
        value: '拼车送天府',
        label: '拼车送天府'
      }, {
        value: '拼车接天府',
        label: '拼车接天府'
      }, {
        value: '送双流',
        label: '送双流'
      },
      {
        value: '接双流',
        label: '接双流'
      }, {
        value: '送东站',
        label: '送东站'
      }, {
        value: '接东站',
        label: '接东站'
      }, {
        value: '送西站',
        label: '送西站'
      }, {
        value: '接西站',
        label: '接西站'
      }, {
        value: '送南站',
        label: '送南站'
      }, {
        value: '接南站',
        label: '接南站'
      }, {
        value: '送集合点',
        label: '送集合点'
      }, {
        value: '接集合点',
        label: '接集合点'
      }, {
        value: '包车',
        label: '包车'
      }],
      routeShort_value: "",


      // 添加客户-弹框
      addCusMd: { state: false },
      // 是否是修改表单
      isUpd: false,
      // 表单-数据对象
      fm: {
        fname: 'addTrafficCarFm',
        sb: { load: false, text: '立即添加' },
        ps: {
          // 操作员
          operator: '',
          // 用车客户              
          useCarUname: '',
          // 乘车人：张三-13588888888            
          routeLink: { name: '', phone: '' },
          // 业务员：张三-13588888888-U8888888888
          serviceMan: { name: '', phone: '', uname: '' },
          // 行程简称           
          routeShort: '',
          // 固定车 eg:0否(默认) 1是；
          fixedCar: 0,
          // 固定人 eg:0否(默认) 1是；
          fixedDriver: 0,

          // 日期起止
          seDate: [],
          // 重复方式 
          repeatWay: [],
          // 去程开始时间
          goStime: '',
          // 去程线路
          goPoints: [],
          // 去程结束时间
          goEtime: '',
          // 间隔天数
          spaceDays: 0,
          // 回程开始时间
          backStime: '',
          // 回程线路
          backPoints: [],
          // 回程结束时间
          backEtime: '',
          // 途径高速       
          wayHighSpeed: '',

          // 座位数           
          seats: '',
          // 车辆数                
          cars: 1,
          // 天数                
          useCarDays: 1,
          // 运价            
          transportPrice: 0,
          // 其他费用       
          otherFees: '',
          // 订单总价         
          orderTotalPrice: '',
          // 定金       
          deposit: '',
          // 师傅现收             
          remindRouteCash: '',
          // 派单价格（修改才有）
          disPrice: '',
          // 行程详情   
          routeDetail: '',
          // 客户备注          
          cusNote: '',
          // 驾驶员备注          
          driverNote: '',
          // 业务员备注         
          salesmanNote: '',
          // 是否通知驾驶员
          isNotice: 0,
        },
      },
      // 重复方式数组
      repeatWayList: [
        { val: 7, text: '法定工作日' },
        { val: 8, text: '法定节假日' },
        { val: 1, text: '星期一' },
        { val: 2, text: '星期二' },
        { val: 3, text: '星期三' },
        { val: 4, text: '星期四' },
        { val: 5, text: '星期五' },
        { val: 6, text: '星期六' },
        { val: 0, text: '星期天' },
      ],
      // 操作员列表
      operatorList: [],
      // 用车客户列表     
      cusList: [],
      // 业务员列表          
      serviceManList: this.allServiceManList,
      // 修改的子订单同级订单列表      
      dg: {
        dgName: 'dg',
        tbName: 'otherTransOrderListTb',
        list: [],
        selRows: [],
      },
    }
  },
  watch: {
    // 监控每日行程数据改变
    'fm.ps': {
      handler(cv, ov) {
        // 自动生成行程详情
        this.creatRouteText();
      },
      deep: true // true=深度监听
    },
  },
  async created() {
    const that = this, U = that.U, ps = that.fm.ps;

    console.log('父级传入数据', that.order);

    // 如果存在回填订单对象
    if (that.order) {
      // 表示修改（如果是复制订单，则显示添加表单，否则就显示修改订单）
      that.isUpd = that.order.isCopy ? false : true;

      // 处理数据
      let o = U.scopy(that.order);

      // 固定车
      ps.fixedCar = o.fixedCar;
      // 固定人 eg:0否(默认) 1是；
      ps.fixedDriver = o.fixedDriver;
      // 去
      let go = o.dayRoutes[0];
      // 去程开始时间
      ps.goStime = go.stime;
      // 去程线路
      let goPoints = [go.spoint];
      if (go.amPoints.length > 0) { go.amPoints.forEach(it => { goPoints.push(it); }); }
      goPoints.push(go.epoint);
      ps.goPoints = goPoints;
      // 去程结束时间
      ps.goEtime = go.etime;
      // 回
      let back = o.dayRoutes[1];
      // 回程开始时间
      ps.backStime = back.stime;
      // 回程线路
      let backPoints = [back.spoint];
      if (back.amPoints.length > 0) { back.amPoints.forEach(it => { backPoints.push(it); }); }
      backPoints.push(back.epoint);
      ps.backPoints = backPoints;
      // 回程结束时间
      ps.backEtime = back.etime;
      // 途径高速（去回一样）      
      ps.wayHighSpeed = back.wayHighSpeed;
      // 座位数           
      ps.seats = o.seats;
      // 派车价格            
      ps.disPrice = o.disPrice;
      // 运价            
      ps.transportPrice = o.transportPrice;
      // 其他费用       
      ps.otherFees = o.otherFees;
      // 师傅现收             
      ps.remindRouteCash = o.remindRouteCash;
      // 行程详情   
      ps.routeDetail = o.routeDetail;
      // 客户备注          
      ps.cusNote = o.cusNote;
      // 驾驶员备注          
      ps.driverNote = o.driverNote;
      // 业务员备注         
      ps.salesmanNote = o.salesmanNote;

      that.fm.ps = Object.assign(that.fm.ps, o);

      // 其他子订单
      let list = that.order.otherOrders || [];
      list.forEach(it => { it.dgName = that.dg.dgName; });
      that.dg.list = list;

      // 获取指定用车单位
      let res = await commonSer.queryComboCusPageList({ page: 1, rows: 20, find: that.order.useCarUname });
      if (res && res.code == 1) {
        that.cusList = res.data;

        // 回填选择客户对应的操作员
        let selCus = that.cusList.find(it => it.baseUserId.uname == that.fm.ps.useCarUname);
        if (selCus) that.selUseCarCus(selCus);
      }

      // 如果是’复制‘功能，则修改按钮名称
      if (that.fm.ps.isCopy) that.fm.sb.text = '立即复制';

      // 自动生成行程详情
      that.creatRouteText();
    }
  },
  methods: {
    /* 关闭弹框 */
    closeMd() {
      this.$emit('getMdState', false);
    },
    // 子组件通信函数
    timeInp(e) {
      this.fm.ps[e.name] = e.val;
    },
    queryCusPageList_change() {
      const that = this;

      commonSer.queryComboCusPageList({ page: 1, rows: 20, find: that.queryCusPageList_find }).then(res => {
        console.log('queryCusPageList_find')
        if (res && res.code == 1) that.cusList = res.data;
      });
    },
    /**
     * 获取-单位客户列表（用于下拉框）
     * @param find 客户手机号/用户名
     */
    queryCusPageList(find) {
      const that = this;

      commonSer.queryComboCusPageList({ page: 1, rows: 20, find: find }).then(res => {
        if (res && res.code == 1) that.cusList = res.data;
      });
    },
    /**
     * 选择-用车客户-获取操作员
     * @param obj 客户对象
     */
    selUseCarCus(obj) {
      const that = this;

      // 检查业务员是否存在业务员列表中
      let sm = that.serviceManList.find(it => it.baseUserId.uname == obj.serviceMan.split('-')[1]);
      if (sm) {
        that.selServiceMan(sm.baseUserId);

        // 设置乘车人信息
        that.fm.ps.routeLink = { name: sm.baseUserId.realName, phone: sm.baseUserId.phone };
      }

      // 根据客户用户名获取对应的操作员列表及选中操作员
      orderService.geDutysByCuList({ cusUname: obj.baseUserId.uname }).then(res => {
        if (res && res.code == 1) {
          that.operatorList = res.data;

          // 设置默认选中值
          that.fm.ps.operator = that.operatorList.length > 0 ? that.operatorList[0].uname : '';
        }
      });
    },
    // 业务员-选择事件
    selServiceMan(obj) {
      const that = this;

      that.fm.ps.serviceMan = {
        name: obj.realName,
        phone: obj.phone,
        uname: obj.uname
      };
    },
    /** 选择-重复方式 */
    selRepeatWay(val) {
      let that = this, repeatWays = that.fm.ps.repeatWay;

      // 当前选中了‘法定工作日’或者‘法定节假日’
      if (repeatWays.length > 0) {
        if (repeatWays[repeatWays.length - 1] == 7) {
          that.fm.ps.repeatWay = [7];
        } else if (repeatWays[repeatWays.length - 1] == 8) {
          that.fm.ps.repeatWay = [8];
        } else {
          that.fm.ps.repeatWay = repeatWays.filter(it => (it != 7 && it != 8));
        }
      }
    },
    // 改变回程线路
    reverseBackPoints(val) {
      // 当去程线路改变时，回程线路相应改变
      this.fm.ps.backPoints = val.reverse();
    },
    /** 生成-行程详情 */
    creatRouteText() {
      const that = this, U = that.U, it = that.fm.ps;

      let rdText = '';

      // 必要的数据都存在，才生成
      if (it.goStime && it.goPoints.length > 0 && it.goEtime && it.backStime && it.backPoints.length > 0 && it.backEtime) {

        // 去程开始时间
        rdText += it.goStime + '出发，';

        // 去程线路
        let goAddrs = '';
        it.goPoints.forEach(it => { goAddrs = `${goAddrs}→${it.name}`; });
        rdText += '途径' + goAddrs.substr(1) + '，';

        // 去程结束时间
        rdText += `${it.goEtime}结束`;

        // 途径高速 （途径都汶高速、京昆高速）
        if (it.wayHighSpeed) rdText += `（途径${it.wayHighSpeed}）`;

        // 增加换行标志
        rdText += `@`;


        // 回程开始时间
        rdText += it.backStime + '出发，';

        // 回程线路
        let backAddrs = '';
        it.backPoints.forEach(it => { backAddrs = `${backAddrs}→${it.name}`; });
        rdText += '途径' + backAddrs.substr(1) + '，';

        // 回程结束时间
        rdText += `${it.backEtime}结束返程`;

        // 途径高速 （途径都汶高速、京昆高速）
        if (it.wayHighSpeed) rdText += `（途径${it.wayHighSpeed}）`;

        that.fm.ps.routeDetail = rdText;
      }
    },

    /*********添加客户弹框***********/
    setAddCusMd(e) {
      const that = this;

      that.addCusMd.state = e.state;
      if (e.routeLink) that.fm.ps.routeLink = e.routeLink;
    },
    // 设置-数据
    setCusDat(e) {
      // 操作员/客户显示为当前添加的客户
      const that = this;

      that.operatorList.push(e);
      that.cusList.push(e);
    },
    // 选择地点后的回调函数
    setPoint(e) {
      let that = this, U = that.U, ps = that.fm.ps;

      if (e.p) {
        ps[e.name] = e.p;

        // 对应点不为空，则取消验证
        if (ps[e.name].length > 0) U.clearFmVali(that, that.fm.fname, `${e.name}`);

        // 同步回程线路
        if (e.name == 'goPoints') ps.backPoints = U.scopy(ps.goPoints).reverse();
      }
    },
    /**
     * 删除-多个地点某个地点
     * @param cindex 删除的天行程下多个地点的下标
     * @param name 删除的地点数组名称
     */
    delMpsItem(cindex, name) {
      let that = this, mps = that.fm.ps[name];

      if (mps[cindex]) mps.splice(cindex, 1);
    },
    // 计算订单总价 
    calcOrderTotalPrice() {
      const that = this, FV = that.FV, ps = that.fm.ps;

      // 运价 车辆数不能为空，否则不计算
      if (!ps.transportPrice || !ps.cars || !FV.isNumber(ps.transportPrice) || !FV.isNumber(ps.cars)) {
        ps.orderTotalPrice = 0;
        return;
      } else {
        let totalPrice = parseFloat(ps.transportPrice) * parseInt(ps.cars);

        // 验证并累计其他费用
        if (FV.isNumber(ps.otherFees) && ps.otherFees) {
          totalPrice += parseFloat(ps.otherFees);
        }

        ps.orderTotalPrice = totalPrice;
      }
    },
    /**
     * 表单提交
     * @param type 类型 1-保存行程订单 2-保存交通车订单 3-保存并继续
     */
    onSubmitFm(type) {
      const that = this, ps = that.U.scopy(that.fm.ps);

      // console.log('订单提交的参数', ps);

      that.$refs[that.fm.fname].validate((valid) => {
        if (!valid) { return false; } else {
          if (type == 3) {// 保存并继续
            that.onSubmit(type);
          } else {// 保存行程订单
            that.onSubmit(type);
          }
        }
      });
    },
    /**
     * 获取-指定行程中的点
     * @param plist 需要处理的地点列表
     * @returns 对象{sp: 起点, ep: 终点, wps: 途径点}
     */
    getPointByType(plist) {
      let res = { sp: '', ep: '', wps: '' };

      if (plist.length > 0 && plist.length <= 2) {
        // 只存在起点和终点
        let sp = plist[0];   // 截取第一位
        res.sp = `${sp.area.split('-')[1]} ${sp.name}=${sp.lnglat}=${sp.area}=${sp.isSta ? 1 : 0}`;

        let ep = plist[plist.length - 1]; // 截取最后一位
        res.ep = `${ep.area.split('-')[1]} ${ep.name}=${ep.lnglat}=${ep.area}=${ep.isSta ? 1 : 0}`;
      } else if (plist.length > 2) {
        // 存在途径点
        let sp = plist[0];   // 截取第一位
        res.sp = `${sp.area.split('-')[1]} ${sp.name}=${sp.lnglat}=${sp.area}=${sp.isSta ? 1 : 0}`;

        let ep = plist[plist.length - 1]; // 截取最后一位
        res.ep = `${ep.area.split('-')[1]} ${ep.name}=${ep.lnglat}=${ep.area}=${ep.isSta ? 1 : 0}`;

        let wps = plist.slice(1, -1); // 截取除第一位和最后一位的所有项

        let wpArr = [];
        wps.forEach(it => {
          wpArr.push(`${it.area.split('-')[1]} ${it.name}=${it.lnglat}=${it.area}=${it.isSta ? 1 : 0}`);
        });
        res.wps = wpArr.join('/@');
      }

      return res;
    },
    /** 选中修改订单同级数据发生改变事件 */
    selRowChange(selection) {
      this.dg.selRows = selection;
    },
    /**
     * 提交表单
     */
    onSubmit(type) {
      const that = this, U = that.U, ps = that.fm.ps;

      that.$refs[that.fm.fname].validate((valid) => {
        if (!valid) { return false; } else {
          that.fm.sb.load = true;
          let loading = this.U.qloading('提交中，请稍后...');

          /*=======处理参数==========*/
          let p = {};
          // 下单客户-用户名
          p.companyCusUname = ps.useCarUname;
          // 下单客户操作员-用户名
          p.dutyService = ps.operator;
          // 乘车人
          p.routeLink = `${ps.routeLink.name}-${ps.routeLink.phone}`;
          // 下单客户业务员
          p.serviceMan = `${ps.serviceMan.uname}-${ps.serviceMan.name}-${ps.serviceMan.phone}`;
          // 行程简称
          p.routeSimpleName = ps.routeShort == '包车' ? that.routeShort_value + ps.routeShort : ps.routeShort;
          // 去程开始时间 eg:小时:分钟(09:00)
          p.goStime = ps.goStime;
          // 去程起点 eg:成都市 天府广场=103.666666,30.666666=四川省-成都市-武侯区
          p.goSpoint = that.getPointByType(ps.goPoints).sp;
          // 去程途径点 eg:成都市 宽窄巷子=103.666666,30.666666=四川省-成都市-武侯区/@成都市 锦里=103.666666,30.666666=四川省-成都市-武侯区
          p.goMorningPoint = that.getPointByType(ps.goPoints).wps;
          // 去程终点 eg:成都市 新城市广场=103.666666,30.666666=四川省-成都市-武侯区
          p.goEpoint = that.getPointByType(ps.goPoints).ep;
          // 去程结束时间 eg:小时:分钟(13:00)
          p.goEtime = ps.goEtime;
          // 返程间隔天数 eg:0
          p.divDays = ps.spaceDays;
          // 返程开始时间 eg:小时:分钟(15:00)
          p.backStime = ps.backStime;
          // 返程起点 eg:成都市 天府广场=103.666666,30.666666=四川省-成都市-武侯区
          p.backSpoint = that.getPointByType(ps.backPoints).sp;
          // 返程途径点 eg:成都市 宽窄巷子=103.666666,30.666666=四川省-成都市-武侯区/@成都市 锦里=103.666666,30.666666=四川省-成都市-武侯区
          p.backMorningPoint = that.getPointByType(ps.backPoints).wps;
          // 返程终点 eg:成都市 新城市广场=103.666666,30.666666=四川省-成都市-武侯区
          p.backEpoint = that.getPointByType(ps.backPoints).ep;
          // 返程结束时间 eg:小时:分钟(19:00)
          p.backEtime = ps.backEtime;
          // 途径高速 eg:成雅，京昆
          p.highSpeed = ps.wayHighSpeed;
          // 需求座位数  eg:30
          p.needSeats = ps.seats;
          // 需求车辆数  eg:3
          p.needCars = ps.cars;
          // 单车运价  eg:3000
          p.eachPrice = ps.transportPrice;
          // 需求天数
          p.useCarDays = ps.useCarDays;
          // 总运价  eg:3000
          p.price = U.num(ps.transportPrice * ps.cars);
          // 其他费用
          p.otherPrice = ps.otherFees;
          // 提醒师傅现收
          p.remDriverCharge = ps.remindRouteCash;
          // 行程详情
          p.routeDetail = ps.routeDetail;
          // 客户备注
          p.cusNote = ps.cusNote;
          // 驾驶员备注
          p.driverNote = ps.driverNote;
          // 业务员备注
          p.serviceNote = ps.salesmanNote;
          // 固定车 eg:0否(默认) 1是
          p.fixedCar = ps.fixedCar;
          // 固定人 eg:0否(默认) 1是
          p.fixedDriver = ps.fixedDriver;
          // 是否通知驾驶员
          p.isNotice = ps.isNotice;

          console.log('交通车提交参数', p);


          if (!that.order || that.order.isCopy == 1) {
            // 交通车开始日期(默认选中日期的开始时间) eg:yyyy-mm-dd HH:mm:ss
            p.transSdate = ps.seDate[0];
            // 交通车结束日期(默认选中日期的结束时间) eg:yyyy-mm-dd HH:mm:ss
            p.transEdate = ps.seDate[1];
            // 交通车重复方式，非法定节假日【7】非法定工作日【8】的可以多个逗号拼接 eg:周一【1】周二【2】周三【3】周四【4】周五【5】周六【6】周日【0】法定节假日【7】法定工作日【8】
            p.transWay = ps.repeatWay.join(',');
            // 定金
            p.handSelPrice = ps.deposit;

            // 添加/复制订单
            orderService.addCompanyTransOrder(p).then(res => {
              that.fm.sb.load = false;
              U.qclose(loading);

              if (!res || res.code != 1) {
                U.qerror(res.msg);
              } else {
                U.qsuccess(res.msg);

                // 关闭弹框
                if (type != 3) that.closeMd();

                // 调用父组件方法-重新加载数据
                that.$emit('reloadDg');
              }
            }).catch(erro => {
              that.fm.sb.load = false;
              U.qclose(loading);
            });
          } else {
            // 订单编号（修改才有）
            if (that.order) p.orderNum = [that.order.orderNum];
            // 所同步修改的子订单编号数组字符串
            that.dg.selRows.forEach(onit => { p.orderNum.push(onit.orderNum); });

            // 修改订单
            orderService.updateTrans(p).then(res => {
              that.fm.sb.load = false;
              U.qclose(loading);

              if (!res || res.code != 1) {
                U.qerror(res.msg);
              } else {
                U.qsuccess(res.msg);

                // 关闭弹框
                that.closeMd();

                // 调用父组件方法-重新加载数据
                that.$emit('reloadDg');
              }
            }).catch(erro => {
              that.fm.sb.load = false;
              U.qclose(loading);
            });
          }
        }
      });
    },

  }
}
</script>
<style lang="less" scoped>
.add-traffic-car ::v-deep {

  .add-traffic-car-fm {
    // 使用弹框的底部滚动条，表单的滚动条隐藏
    min-width: 1520px;
    overflow-x: hidden;
  }

  .upd-traffic-car-fm {
    // 使用弹框的底部滚动条，表单的滚动条隐藏
    min-width: 1415px;
    overflow-x: hidden;
  }

  .el-textarea textarea {
    height: 150px !important;
  }

  // 添加用车客户
  .add-btn {
    position: absolute;
    right: -20px;
    bottom: 6px;
    cursor: pointer;
  }

  .jt-car-line {

    &>div>div {
      margin-left: 0px !important;
    }
  }

  // 去程/回程线路
  .go-points,
  .back-points {
    .el-input__inner {
      cursor: pointer;
    }

    .el-input-group__append {
      padding: 0 5px;
    }
  }

  .text-note .el-form-item .el-form-item__label {
    line-height: 18px;
  }

  .page-explain {
    border-top: 1px solid #efefef;
    margin-top: 10px;
    padding: 10px 0;

    span {
      color: #666 !important;
      font-size: 12px !important;
    }
  }

}
</style>
